<template>
  <CrudTable
    :buttons="tableButtons"
    row-selection-type="multiple"
    :columns="tableColumns"
    @currentChange="handleSelectChange"
    :tableData="pageData.tableData.records"
    :loading="pageData.loading"
    :pagination="pageData.pagination"
    @pageChange="handlePageChange"
    @rowDbClick="handleRowDbClick"
    :showRefresh="true"
    :showExport="false"
    @refreshData="handleTableRefresh"
    :filterValue="pageData.filterValue"
    @filterChange="filterChange"
    :rowOpWidth="300"
  >
    <template #rowOperations="{ row }">
      <div class="crud-table__row_operations">
        <t-link variant="text" theme="primary" @click="handleOperateRow('download', row)">下载附件</t-link>
        <t-link variant="text" theme="primary" @click="handleOperateRow('view', row)">查看信息</t-link>
        <t-link variant="text" theme="primary" @click="handleOperateRow('edit', row)">修改信息</t-link>
        <t-link variant="text" theme="danger" @click="handleOperateRow('delete', row)">删除附件</t-link>
      </div>
    </template>
  </CrudTable>

  <EditForm
    v-if="pageData.showEditForm"
    :dialogVisible="pageData.showEditForm"
    :mode="pageData.editFormMode"
    :id="pageData.selectedRowId"
    @close="handleDialogClose"
  />
  <UpLoadDialog v-if="pageData.showUpLoadDialog" :showDialog="pageData.showUpLoadDialog" @onClose="handleUploadClose" />
</template>

<script lang="tsx" setup>
// 框架和组件库
import { ref, computed, reactive, defineAsyncComponent } from "vue";
import { DialogPlugin, MessagePlugin, type TableProps } from "tdesign-vue-next";

// TS 类型文件
import type { ICrudTableDataPage, TFilterValue } from "@/types";

// 工具函数
import { http } from "@/utils/fetch";
import { newPrecision } from "@/utils/tools";

// 常量
import { PAGINATION_VALUE } from "@/common/constants";

// API
import { downloadFileStream } from "@/api/file";

const UpLoadDialog = defineAsyncComponent(() => import("./components/UpLoad.vue"));
const EditForm = defineAsyncComponent(() => import("./components/EditForm.vue"));

const GET_LIST_PATH = "/media/findAll"; // 查询媒体信息接口
const DELETE_ITEM_PATH = "/media/delete"; // 删除接口

const pageData = reactive({
  loading: false,
  tableData: {} as ICrudTableDataPage,
  selectedRow: {},
  selectedRowId: "",
  selectedRowsEvent: {},
  showEditForm: false,
  showUpLoadDialog: false,
  editFormMode: "",
  filterValue: {
    // id: "",
    // userName: "",
    // gender: "",
    // status: ""
  } as TFilterValue,
  pagination: {
    pageSize: 20,
    total: 0,
    current: 1
  }
});

// 表格操作按钮配置
const tableButtons = computed(() => [
  {
    name: "上传媒体文件",
    click: () => {
      pageData.showUpLoadDialog = true;
    }
  }
  // {
  //   name: "新增媒体记录",
  //   click: () => {
  //     pageData.editFormMode = "new";
  //     pageData.showEditForm = true;
  //   }
  // },
]);

// 表格列配置
const tableColumns = ref<TableProps["columns"]>([
  {
    colKey: "name",
    title: "文件名",
    width: 250,
    filter: {
      type: "input",
      resetValue: "",
      // 按下 Enter 键时也触发确认搜索
      confirmEvents: ["onEnter"],
      showConfirmAndReset: true
    }
  },
  {
    colKey: "size",
    title: "大小（MB）",
    width: 120,
    cell: (h, { row }) => {
      return newPrecision(row.size / 1000000, 3);
    }
  },
  {
    colKey: "type",
    title: "类型",
    width: 200
  }
  // {
  //   colKey: "path",
  //   title: "路径",
  //   width: 150
  // }
]);

// 获取列表数据
const findAllList = async () => {
  pageData.loading = true;
  const resultData = await http(
    "GET",
    `${GET_LIST_PATH}?page=${pageData.pagination.current}&pageSize=${pageData.pagination.pageSize}`
  );
  if (resultData.code === 200) {
    pageData.tableData = resultData.data;
    pageData.pagination.total = resultData.data.total;
    pageData.pagination.current = resultData.data.current;
    pageData.pagination.pageSize = resultData.data.size;
    pageData.loading = false;
  }
};

const handlePageChange = (pageInfo: Record<string, any>, newDataSource: Record<string, any>) => {
  console.log(pageInfo, newDataSource);
  pageData.pagination.pageSize = pageInfo.pageSize;
  pageData.pagination.current = pageInfo.current;
  findAllList();
};

// 过滤事件触发函数
const filterChange = (filters: Record<string, any>) => {
  pageData.filterValue = filters;
  pageData.pagination = structuredClone(PAGINATION_VALUE);
  findAllList();
};

const handleTableRefresh = () => {
  pageData.selectedRow = {};
  pageData.selectedRowId = "";
  pageData.pagination = structuredClone(PAGINATION_VALUE);
  pageData.filterValue = {};
  findAllList();
};

const handleRowDbClick = (context: Record<string, any>) => {
  handleOperateRow("view", context.row);
};

const handleOperateRow = (mode: string, row?: Record<string, any>) => {
  if (mode === "download") {
    downloadFileStream(row!.id);
  } else {
    if (mode !== "delete") {
      if (mode === "new") {
        pageData.selectedRow = {};
        pageData.selectedRowId = "";
      } else {
        pageData.selectedRow = row!;
        pageData.selectedRowId = row!.id;
      }
      pageData.editFormMode = mode;
      pageData.showEditForm = true;
    } else if (mode === "delete") {
      const confirmDialog = DialogPlugin({
        header: "警告",
        body: "确定要删除这一条数据吗？",
        confirmBtn: "确定",
        cancelBtn: "取消",
        onConfirm: async () => {
          const deleteData = await http("DELETE", `${DELETE_ITEM_PATH}?id=${row!.id}`);
          if (deleteData.code === 200) {
            MessagePlugin.success("删除成功！");
            findAllList();
            confirmDialog.hide();
          }
        },
        onClose: () => {
          confirmDialog.hide();
        }
      });
    } else {
      MessagePlugin.error("错误：未知的表格操作模式。");
    }
  }
};

const handleSelectChange = (e: Record<string, any>) => {
  pageData.selectedRowsEvent = e;
};

// 对话框关闭时的处理函数
const handleDialogClose = (e: string) => {
  if (e === "success") {
    MessagePlugin.success("操作成功！");
    findAllList();
  }
  pageData.showEditForm = false;
};

const handleUploadClose = () => {
  findAllList();
  pageData.showUpLoadDialog = false;
};

// 初始化列表
findAllList();
</script>
